﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Wikipedia Lookup</title>
    <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
    <script type="text/javascript" src="Scripts/rx.js"></script>
    <script type="text/javascript" src="Scripts/rx.jquery.js"></script>
    <script type="text/javascript">
        $(function () {
            function searchWikipedia(term) {
                return $.ajaxAsObservable({
                    url: 'http://en.wikipedia.org/w/api.php',
                    dataType: 'jsonp',
                    data: {
                        action: 'opensearch',
                        search: term,
                        format: 'json'
                    }
                })
                .Select(function (d) {
                    return d.data[1];
                });
            }

            var input = $('#textbox').toObservable('keyup')
                .Select(function (ev) {
                    return $(ev.target).val();
                })
                .Throttle(250)
                .DistinctUntilChanged();

            var searchObservable = input.Select(searchWikipedia).Switch();
            var subscription = searchObservable.Subscribe(
                function (results) {
                    $('#results').empty();
                    $.each(results, function (_, result) {
                        $('#results').append('<li>' + result + '</li>');
                    });
                },
                function (ex) {
                    $('#error').text(ex);
                });
        });
    </script>
</head>
<body>
    <input id="textbox" type="text" size="100" /><br />
    <ul id="results"></ul>
    <p id="error"></p>
</body>
</html>
